package cn.sugela.aichat.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.sugela.aichat.dto.Message;
import cn.sugela.aichat.dto.ChatResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ryan
 * @date 2023-03-28 10:11:57
 */
@RestController
@RequestMapping("/v1/chat")
public class ChatController {

    @RequestMapping("/completions")
    public ChatResult completions(@RequestBody Message message) {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json;charset=UTF-8");

        JSONObject json = new JSONObject();
        // 选择模型
        json.set("model", "text-davinci-003");
        // 添加我们需要输入的内容
        json.set("prompt", message.getText());
        // 情绪值
        json.set("temperature", 0.9);

        json.set("max_tokens", 2048);
        // 相似度
        json.set("top_p", 1);
        json.set("frequency_penalty", 0.0);
        json.set("presence_penalty", 0.6);

        HttpResponse response = HttpRequest.post("https://api.openai.com/v1/completions")
                .headerMap(headers, false)
                .bearerAuth("自己的key")
                .body(String.valueOf(json))
                .timeout(5 * 60 * 1000)
                .execute();
        String body = response.body();
        JSONObject jsonObject = JSON.parseObject(body, JSONObject.class);
        Object choices = jsonObject.get("choices");
        JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(choices));

        ChatResult chatResult = new ChatResult();
        if (jsonArray != null && jsonArray.size() > 0) {
            String text = JSON.toJSONString(jsonArray.get(0));
            JSONObject resultObj = JSON.parseObject(text, JSONObject.class);
            Object text1 = resultObj.get("text");
            chatResult.setText(text1.toString());
        }
        return chatResult;
    }

}
